package com.sp.scmdb.action;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
import java.util.Set;

import net.sf.json.JSONArray;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.sp.scmdb.bean.MonitorBean;
import com.sp.scmdb.bean.MonitorDepBean;
import com.sp.scmdb.bean.MonitorReaderBean;
import com.sp.scmdb.bean.ReaderMapBean;
import com.sp.scmdb.bean.UserBean;
import com.sp.scmdb.common.CommonParamter;
import com.sp.scmdb.common.action.BaseAction;
import com.sp.scmdb.entity.AlarmType;
import com.sp.scmdb.entity.Area;
import com.sp.scmdb.entity.Department;
import com.sp.scmdb.entity.LabelReadingMachine;
import com.sp.scmdb.entity.Map;
import com.sp.scmdb.entity.WorkType;
import com.sp.scmdb.service.AlarmService;
import com.sp.scmdb.service.AreaService;
import com.sp.scmdb.service.DepartmentService;
import com.sp.scmdb.service.MapService;
import com.sp.scmdb.service.MonitorService;
import com.sp.scmdb.service.ReaderService;
import com.sp.scmdb.service.WorkTypeService;

@Controller("monitorAction")
@Scope("prototype")
public class MonitorAction extends BaseAction<MonitorBean> {

	private static final long serialVersionUID = 1L;
	private static Log log = LogFactory.getLog(MonitorAction.class);

	private MapService mapService;
	private DepartmentService departmentService;
	private WorkTypeService workTypeService;
	private MonitorService monitorService;
	private AreaService areaService;
	private ReaderService readerService;
	private AlarmService alarmService;

	private InputStream imagStream;
	private String result;
	private String department;
	private String workType;

	private String sectionNo;

	public void setSectionNo(String sectionNo) {
		this.sectionNo = sectionNo;
	}

	public String getSectionNo() {
		return sectionNo;
	}

	@SuppressWarnings("unchecked")
	private Connection getDBConnection(String dbURL, String driverName,
			String userName, String password) {
		Connection dbConn = null;
		try {
			Class.forName(driverName);
			dbConn = DriverManager.getConnection(dbURL, userName, password);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return dbConn;
	}

	@SuppressWarnings("unchecked")
	private ArrayList<Integer> getRingInfo(String sectionNo) {
		Connection connRing = null;
		ArrayList<Integer>  arr = new ArrayList<Integer>();
		Properties prop = new Properties();
		InputStream in = getClass().getResourceAsStream("/additionalJdbc.properties");
		try {
			prop.load(in);
		} catch (IOException e1) {
			e1.printStackTrace();
		}

		try {
			connRing = getDBConnection(prop.getProperty("ringInfo.jdbc.url"), prop.getProperty("ringInfo.jdbc.driverClass"), prop.getProperty("ringInfo.jdbc.user"), prop.getProperty("ringInfo.jdbc.password"));
			String sql = "SELECT DISTINCT * FROM sys_ring where section_no="
					+ sectionNo + ";";
			PreparedStatement ps = connRing.prepareStatement(sql);
			ResultSet rs = ps.executeQuery();
			while(rs.next()){
				arr.add(rs.getInt("ring_no"));
			}
			ps.close();
			rs.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (connRing != null) {
				try {
					connRing.close();
				} catch (Exception e) {
				}
			}
		}
		return arr;
	}

	@SuppressWarnings("unchecked")
	private ArrayList getSection1Info() {
		Connection connSection1 = null;
		ArrayList<Integer> arrRingSection1 = getRingInfo("1");
		ArrayList list = new ArrayList();
		Properties prop = new Properties();
		InputStream in = getClass().getResourceAsStream("/additionalJdbc.properties");
		try {
			prop.load(in);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		
		try {
			connSection1 = getDBConnection(prop.getProperty("section1.jdbc.url"), prop.getProperty("section1.jdbc.driverClass"), prop.getProperty("section1.jdbc.user"), prop.getProperty("section1.jdbc.password"));
			String sql = "SELECT * FROM sj1 where 记录时间=(select max(记录时间) from sj1);";
			PreparedStatement ps = connSection1.prepareStatement(sql);
			ResultSet rs = ps.executeQuery();
			rs.next();
			Integer ring_no = rs.getInt("环号");
			Integer processRecord = rs.getInt("推进行程");
			Time recordTime = rs.getTime("记录时间");
			ps.close();
			rs.close();
			list.add(ring_no.toString());
			list.add(processRecord.toString());
			list.add(recordTime.toString());
			
			ArrayList<String> tmp = new ArrayList<String>();
			Boolean b = false;
			for (int i = 0; i <= ring_no; ++i) {
				b = false;
				for (Integer obj : arrRingSection1) {
					if (obj == i) {
						b = true;
						break;
					}
				}
				if (!b) {
					tmp.add(((Integer)i).toString());
				}
			}
			list.add(tmp);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (connSection1 != null) {
				try {
					connSection1.close();
				} catch (Exception e) {
				}
			}
		}

		return list;
	}

	@SuppressWarnings("unchecked")
	private ArrayList getSection2Info() {
		Connection connSection2 = null;
		ArrayList<Integer> arrRingSection2 = getRingInfo("2");
		ArrayList list = new ArrayList();
		Properties prop = new Properties();
		InputStream in = getClass().getResourceAsStream("/additionalJdbc.properties");
		try {
			prop.load(in);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		
		try {
			connSection2 = getDBConnection(prop.getProperty("section2.jdbc.url"), prop.getProperty("section2.jdbc.driverClass"), prop.getProperty("section2.jdbc.user"), prop.getProperty("section2.jdbc.password"));
			String sql = "SELECT * FROM sj1 where 记录时间=(select max(记录时间) from sj1);";
			PreparedStatement ps = connSection2.prepareStatement(sql);
			ResultSet rs = ps.executeQuery();
			rs.next();
			Integer ring_no = rs.getInt("环号");
			Integer processRecord = rs.getInt("推进行程");
			Time recordTime = rs.getTime("记录时间");
			ps.close();
			rs.close();
			list.add(ring_no.toString());
			list.add(processRecord.toString());
			list.add(recordTime.toString());
			
			ArrayList<String> tmp = new ArrayList<String>();
			Boolean b = false;
			for (int i = 0; i <= ring_no; ++i) {
				b = false;
				for (Integer obj : arrRingSection2) {
					if (obj == i) {
						b = true;
						break;
					}
				}
				if (!b) {
					tmp.add(((Integer)i).toString());
				}
			}
			list.add(tmp);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (connSection2 != null) {
				try {
					connSection2.close();
				} catch (Exception e) {
				}
			}
		}

		return list;
	}
	
	@SuppressWarnings("unchecked")
	private ArrayList getSection3Info() {
		return new ArrayList();
	}
	
	@SuppressWarnings("unchecked")
	private ArrayList getSection4Info() {
		return new ArrayList();
	}
	
	@SuppressWarnings("unchecked")
	public String getProcessInfo() {
		try {
			HashMap<String, ArrayList> m = new HashMap<String, ArrayList>();
			m.put("1", getSection1Info());
			m.put("2", getSection2Info());
			m.put("3", getSection3Info());
			m.put("4", getSection4Info());
			JSONArray jo = JSONArray.fromObject(m);
			result = jo.toString();
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return "fail";
		} finally {
		}
	}

	@SuppressWarnings("unchecked")
	public String getReaderMap() {
		try {
			List<ReaderMapBean> ret = monitorService.findReaderMapData();
			JSONArray jo = JSONArray.fromObject(ret);
			result = jo.toString();
			return SUCCESS;
		} catch (Exception e) {
			log.error("getReaderMap failed! reason:" + e.getMessage());
			return "fail";
		}
	}

	@SuppressWarnings("unchecked")
	public String monitorShow() {
		try {
			UserBean user = (UserBean) session.get("user");
			// 获取园下实时数据
			entity = monitorService.findRealData(entity, department, workType,
					user);
			// 将entity转换成json
			JSONArray jo = JSONArray.fromObject(entity);
			result = jo.toString();

			session
					.put("areaListType", CommonParamter.TypeCommon
							.getAreaType());
			return SUCCESS;
		} catch (Exception e) {
			log.error("init reader failed! reason:" + e.getMessage());
			return "fail";
		}
	}

	public String getRefreshTime() {

		// 将entity转换成json
		JSONArray jo = JSONArray.fromObject(monitorService.getUsedPatameter());
		result = jo.toString();

		return SUCCESS;
	}

	@SuppressWarnings("unchecked")
	public String initMonitor() {
		// 取部门列表
		UserBean user = (UserBean) session.get("user");
		List<Department> listDepartment = departmentService.queryAll(user);
		request.setAttribute("listDepartment", listDepartment);
		// 工种列表
		List<WorkType> listWorkType = workTypeService.queryAll();
		request.setAttribute("listWorkType", listWorkType);
		// 读头列表
		List<LabelReadingMachine> listRead = readerService.queryAll();
		request.setAttribute("listRead", listRead);
		// 地图列表
		List<Map> listMap = mapService.queryIsUsed();
		session.put("listMap", listMap);
		// 区域列表
		List<Area> listArea = areaService.queryAllArea();
		request.setAttribute("listArea", listArea);
		session.put("areaListType", CommonParamter.TypeCommon.getAreaType());

		// 报警类型列表
		List<AlarmType> listAlarmType = alarmService.findAllAlarmType();
		request.setAttribute("listAlarmType", listAlarmType);

		// 刷新时间
		String refreshTime = monitorService.getUsedPatameter().getRefreTime();
		if (StringUtils.isNotEmpty(refreshTime)) {
			if (Integer.parseInt(refreshTime) < 5) {
				refreshTime = "10";
			}
			request.setAttribute("refreshTime", refreshTime);
		} else {
			request.setAttribute("refreshTime", "10");
		}

		return "init";
	}

	public String getMap() {
		List<Map> listMap = mapService.queryIsUsed();
		if (CollectionUtils.isNotEmpty(listMap)) {
			imagStream = new ByteArrayInputStream(listMap.get(0).getMapAddr());
		}
		return "mapImag";
	}

	public String monitorDep() {
		List<MonitorDepBean> depCountList = monitorService.depCountList();
		request.setAttribute("depCountList", depCountList);
		return "monitorDep";
	}

	public String monitorRead() {
		List<MonitorReaderBean> readerCountList = monitorService
				.readerCountList();
		request.setAttribute("readerCountList", readerCountList);
		return "monitorReader";
	}

	@Autowired
	public void setMapService(MapService mapService) {
		this.mapService = mapService;
	}

	@Autowired
	public void setDepartmentService(DepartmentService departmentService) {
		this.departmentService = departmentService;
	}

	@Autowired
	public void setWorkTypeService(WorkTypeService workTypeService) {
		this.workTypeService = workTypeService;
	}

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}

	public String getWorkType() {
		return workType;
	}

	public void setWorkType(String workType) {
		this.workType = workType;
	}

	public String getDepartment() {
		return department;
	}

	public void setDepartment(String department) {
		this.department = department;
	}

	public void setMonitorService(MonitorService monitorService) {
		this.monitorService = monitorService;
	}

	public void setAreaService(AreaService areaService) {
		this.areaService = areaService;
	}

	public void setReaderService(ReaderService readerService) {
		this.readerService = readerService;
	}

	public void setAlarmService(AlarmService alarmService) {
		this.alarmService = alarmService;
	}

	public InputStream getImagStream() {
		return imagStream;
	}

	public void setImagStream(InputStream imagStream) {
		this.imagStream = imagStream;
	}
}
